package org.oschina.helper.messagequeue.impl;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.commons.lang.StringUtils;
import org.oschina.helper.JsonHelper;
import org.oschina.helper.activemq.ActiveMQHelper;
import org.oschina.helper.activemq.JmsType;
import org.oschina.helper.messagequeue.IMessageQueueHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

/**
 * 消息队列实现类
 *  activemq
 */
@Component
public class ActiveMQMessageQueueHelperImpl implements IMessageQueueHelper {

	private final static Logger logger=LoggerFactory.getLogger(ActiveMQMessageQueueHelperImpl.class);
	
	@Autowired
	private ActiveMQHelper activeMQHelper;
	
	@Override
	public boolean send(String key, final Object message)
	{
		if(StringUtils.isBlank(key))
			return false;
		
		activeMQHelper.getTemplate(key, JmsType.QUEUE).send(new MessageCreator()
		{
			@Override
			public Message createMessage(Session session) throws JMSException
			{
				return session.createTextMessage(JsonHelper.toJson(message));
			}
		});
		return true;
	}
	
	@Override
	public <T> Object get(String key, Class<T> type)
	{
		if(StringUtils.isBlank(key))
			return null;
		
		TextMessage message=(TextMessage) activeMQHelper.getTemplate(key, JmsType.QUEUE).receive();
		if(message!=null)
		{
			try
			{
				return JsonHelper.parse(message.getText(), type);
			}
			catch (JMSException e)
			{
				logger.error("jms - 获取消息队列异常 - ",e);
			}
		}
		return null;
	}

}